package httpurlutil

import (
	"github.com/google/uuid"
	"gmap-backend/internal/util/commonutil"
	"strings"
)

func GetRootUrl(url string) string {
	// 去掉查询字符串部分
	ind := strings.Index(url, "?")
	if ind > 0 {
		url = url[:ind]
	}

	uuidStr := strings.ToLower(strings.ReplaceAll(uuid.NewString(), "-", ""))
	url = strings.Replace(url, "://", uuidStr, 1)

	// 如果路径中包含 / ，取之前的部分作为根路径，否则用全部路径作为根路径
	ind = strings.Index(url, "/")
	if ind > 0 {
		url = url[:ind]
	}
	url = strings.TrimSpace(strings.Replace(url, uuidStr, "://", 1))
	return url
}

func CombineUrl(url, rootUrl, subUrl string) string {
	if strings.HasPrefix(subUrl, "https://") || strings.HasPrefix(subUrl, "http://") {
		return subUrl
	}
	if strings.HasPrefix(subUrl, "//") {
		if strings.HasPrefix(url, "https://") {
			return "https:" + subUrl
		}
		if strings.HasPrefix(url, "http://") {
			return "http:" + subUrl
		}
	}
	if strings.HasPrefix(subUrl, "/") {
		return rootUrl + subUrl
	}
	if strings.HasPrefix(subUrl, "./") {
		subUrl = subUrl[len("./"):]
	}
	uuidStr := commonutil.GetUuid()
	url = strings.Replace(url, "://", uuidStr, 1)
	ind := strings.LastIndex(url, "/")
	if ind > 0 {
		return strings.Replace(url[:ind], uuidStr, "://", 1) + "/" + subUrl
	}
	return strings.Replace(url, uuidStr, "://", 1) + "/" + subUrl
}
